import {Types} from "mongoose"
import {detectStockOfLips} from "../../../api/games/lipStickGame";
import {LipstickSeriesModel} from "../../../database/models/lipstickSeries";
import {ProductModel} from "../../../database/models/Product";
import {
  DEFAULT_DAPAN_THRESHOLD_RATE,
  DEFAULT_THRESHOLD_RATE,
  SeriesIncomeThresholdModel
} from "../../../database/models/seriesIncomeThreshold";

export const typeDefs = `
type Series{
  _id: String!
  brand: String!
  name:  String!
  seriesPrice: Float!
  underLinePrice: Float!
  priceInCoin: Int!
  priceInFangka: Int!
  coverUrl: String!
  description: String!
  onStock: Boolean!
  products: [Product]!
  details: [String]!
  createAt: String!
  updateAt: String!
  category: String!
  thresholdRate: Float
  dapanThresholdRate: Float
  sortNum: Int!
  hotNum: Int!
}

input SeriesInput {
  brand: String!
  name:  String!
  seriesPrice: Float!
  underLinePrice: Float!
  priceInCoin: Int!
  priceInFangka: Int!
  coverUrl: String
  description: String!
  onStock: Boolean!
  products: [String]!
  details: [String]!
  createAt: String!
  updateAt: String!
  category: String!
  thresholdRate: Float
  dapanThresholdRate: Float
  sortNum: Int!
  hotNum: Int!
}

input SeriesUpdateInput {
  brand: String
  name:  String
  seriesPrice: Float
  underLinePrice: Float
  priceInCoin: Int!
  priceInFangka: Int!
  coverUrl: String
  description: String
  onStock: Boolean
  details: [String]
  category: String
  thresholdRate: Float
  dapanThresholdRate: Float
  updateAt: String!
  sortNum: Int!
  hotNum: Int!
}
`
export const queryDefs = `
  serieses: [Series!]!
  series(_id: String!): Series
  searchPress(query:String!): [Series]!
  searchSerieses(query:String!): [Series]!
`

export const mutationDefs = `
  createSeries(series:SeriesInput): Series
  onSeries(_id:String!): Series
  offSeries(_id:String!): Series
  deleteSeries(_id:String!): Boolean!
  removeProductFromSeries(_id:String!,productId:String!): Series
  addProductToSeries(_id:String!,productId:String!): Series
  updateSeries(_id: String!,series:SeriesUpdateInput!): Series
`

const getThresholdRate = async _id => {
  const threshold = await SeriesIncomeThresholdModel.findOne({lipstickSeries: Types.ObjectId(_id)}).lean()
  return threshold ? threshold.thresholdCoinRate || DEFAULT_THRESHOLD_RATE : DEFAULT_THRESHOLD_RATE
}
const getDapanThresholdRate = async _id => {
  const threshold = await SeriesIncomeThresholdModel.findOne({lipstickSeries: Types.ObjectId(_id)}).lean()
  return threshold ? threshold.dapanThresholdCoinRate || DEFAULT_DAPAN_THRESHOLD_RATE : DEFAULT_DAPAN_THRESHOLD_RATE
}

export const resolvers = {
  Query: {
    series: async (_, {_id}) => {
      const lip = await LipstickSeriesModel.findById(_id).lean()
      lip[`thresholdRate`] = await getThresholdRate(lip._id)
      lip[`dapanThresholdRate`] = await getDapanThresholdRate(lip._id)
      return lip
    },
    serieses: async () => {
      const lips = await LipstickSeriesModel.find().sort({sortNum: -1, createAt: -1}).lean()
      for (const it of lips) {
        if (it.category === `lipstick`) {
          it[`thresholdRate`] = await getThresholdRate(it._id)
          it[`dapanThresholdRate`] = await getDapanThresholdRate(it._id)
        }
      }
      return lips
    },
    searchPress: async (_, {query}) => {
      const reg = new RegExp(query, 'gi')
      return await LipstickSeriesModel.find({
        name: reg, category: 'lipstick'
      }).lean()
    },
    searchSerieses: async (_, {query}) => {
      const reg = new RegExp(query, 'gi')
      const ses = await LipstickSeriesModel.find({
        name: reg
      }).lean()
      for (const lip of ses) {
        lip[`thresholdRate`] = await getThresholdRate(lip._id)
        lip[`dapanThresholdRate`] = await getDapanThresholdRate(lip._id)
      }
      return ses
    }
  },
  Mutation: {
    async updateSeries(_, {_id, series}) {
      const updatedSeries = await LipstickSeriesModel.findByIdAndUpdate(_id, {...series, updateAt: new Date(series.updateAt)}, {new: true})
      console.log(series)
      if (updatedSeries.category === `lipstick`) {
        const k = await SeriesIncomeThresholdModel.findOneAndUpdate(
          {lipstickSeries: updatedSeries._id},
          {
            $set: {
              thresholdCoinRate: series.thresholdRate || DEFAULT_THRESHOLD_RATE,
              dapanThresholdCoinRate: series.dapanThresholdRate || DEFAULT_DAPAN_THRESHOLD_RATE,
              updateAt: new Date()
            }
          },
          {upsert: true, setDefaultsOnInsert: true, new: true}
        )
        console.log(k)
      }
      const onStock = await detectStockOfLips(updatedSeries.id)
      if (!onStock) {
        throw Error(`该系列中的商品均无库存，已自动下架`)
      }
      return updatedSeries
    },
    async createSeries(_, {series}) {
      const lipstickSeries = await LipstickSeriesModel.create({
        ...series, createAt: new Date(series.createAt), updateAt: new Date(series.updateAt)
      })
      if (lipstickSeries.category === `lipstick`) {
        const k = await SeriesIncomeThresholdModel.findOneAndUpdate(
          {lipstickSeries: lipstickSeries._id},
          {
            $set: {
              thresholdCoinRate: series.thresholdRate || DEFAULT_THRESHOLD_RATE,
              dapanThresholdCoinRate: series.dapanThresholdRate || DEFAULT_DAPAN_THRESHOLD_RATE,
              updateAt: new Date()
            }
          },
          {upsert: true, setDefaultsOnInsert: true}
        )
      }
      if (!(await detectStockOfLips(lipstickSeries._id))) {
        throw Error(`该系列中的商品均无库存，已自动下架`)
      }
      return lipstickSeries
    },
    async removeProductFromSeries(_, {_id, productId}) {
      const lss = await LipstickSeriesModel.findById(_id)

      if (lss) {
        const pIndex = lss.products.findIndex(objId => objId.toString() === productId)
        if (pIndex < 0) {
          throw Error('DONT_HAS_THIS_PRODUCT')
        }
        lss.products.splice(pIndex, 1)
        await lss.save()
        return lss
      }
      throw Error('NO_SUCH_LIPSTICK_SERIES')
    },
    async addProductToSeries(_, {_id, productId}) {
      const lss = await LipstickSeriesModel.findById(_id)

      if (lss) {
        const p = lss.products.find(objId => objId.toString() === productId)
        if (p) {
          throw Error('ALREADY_HAS_THIS_PRODUCT')
        }
        lss.products.push(productId)
        await lss.save()
        return lss
      }
      throw Error('NO_SUCH_LIPSTICK_SERIES')
    },

    async onSeries(_, {_id}) {

      const lss = await LipstickSeriesModel.findById(_id)
      const onStock = await detectStockOfLips(lss.id)
      if (!onStock) {
        lss.onStock = false
        await lss.save()
        throw Error(`该系列中的商品均无库存，已自动下架`)
      } else {
        lss.onStock = true
        await lss.save()
        return lss
      }
    },
    async offSeries(_, {_id}) {

      const lss = await LipstickSeriesModel.findById(_id)
      if (lss) {
        lss.onStock = false
        await lss.save()
        return lss
      }
      throw Error('NO_SUCH_LIPSTICK_SERIES')
    },
    deleteSeries: async (_, {_id}) => {
      return await LipstickSeriesModel.deleteOne({_id})
    }
  },

  Series: {
    products({products}) {
      return ProductModel.find({_id: {$in: products}})
    }
  }

}
